import React, { useState, useRef } from 'react';
import {
  View,
  Text,
  Image,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  LayoutAnimation,
} from 'react-native';

interface NavItem {
  icon: string;
  label: string;
}

const navItems: NavItem[] = [
  {
    icon: 'https://img12.360buyimg.com/babel/jfs/t20270715/38278/23/22574/7960/6694edb4F07db03e3/d663cd498321eadc.png',
    label: '京东超市',
  },
  {
    icon: 'https://m.360buyimg.com/babel/jfs/t20270715/237082/37/21845/7616/6694edddFc764124a/38d00b686257b0f4.png',
    label: '京东电器',
  },
  {
    icon: 'https://img20.360buyimg.com/babel/jfs/t20270715/36751/25/21385/7651/6694ee02F878cddef/13ce837dd39ad1ad.png',
    label: '服饰美妆',
  },
  {
    icon: 'https://img20.360buyimg.com/babel/jfs/t20270715/44839/8/24550/7935/6694ee27F8775a577/b63c6a2fa0327964.png',
    label: '充值中心',
  },
  {
    icon: 'https://img14.360buyimg.com/babel/jfs/t20270715/243181/3/13649/9018/6694ee5fF6aa391d4/1b020aa3f9cf89a0.png',
    label: 'PLUS会员',
  },
  {
    icon: 'https://m.360buyimg.com/babel/jfs/t20270715/22456/27/20943/10381/6694ee81F684396bb/0ba51f592d28dfdd.png',
    label: '京东生鲜',
  },
  {
    icon: 'https://img11.360buyimg.com/babel/jfs/t20270715/29760/28/21267/11992/6694eea3F0fe3dca2/d5672661722bfc42.png',
    label: '京东国际',
  },
  {
    icon: 'https://img10.360buyimg.com/babel/jfs/t20270715/233990/3/23983/8102/6694eec4F2aad82cf/2144631769da49b9.png',
    label: '京东拍卖',
  },
  {
    icon: 'https://img20.360buyimg.com/babel/jfs/t20270926/241563/14/18702/9401/66f4bc8aFc8e6d309/ed7c86f700aba111.png',
    label: '红包惊喜',
  },
  {
    icon: 'https://img14.360buyimg.com/babel/jfs/t20270715/42046/6/20985/8690/6694ef01Ff3769032/bfa11aada78ce515.png',
    label: '全部',
  },
];

const PAGE_SIZE = 10;
const SwiperNav: React.FC = () => {
  const [activeIndex, setActiveIndex] = useState(0);
  const flatListRef = useRef<FlatList>(null);

  const pages = [];
  for (let i = 0; i <= navItems.length; i += PAGE_SIZE) {
    pages.push(navItems.slice(i, i + PAGE_SIZE));
  }

  const handleMomentumScrollEnd = (event: any) => {
    const offsetX = event.nativeEvent.contentOffset.x;
    const width = event.nativeEvent.layoutMeasurement.width;
    const newActiveIndex = Math.floor(offsetX / width);

    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    setActiveIndex(newActiveIndex);
  };

  const handleIndicatorPress = (index: number) => {
    if (flatListRef.current) {
      flatListRef.current.scrollToIndex({ index, animated: true });
    }
  };

  return (
    <View style={styles.container}>
      <FlatList
        ref={flatListRef}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        data={pages}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item: page, index: pageIndex }) => (
          <View style={styles.page}>
            {page.map(
              (
                tab: {
                  icon: string;
                  label:
                    | string
                    | number
                    | bigint
                    | boolean
                    | React.ReactElement<
                        unknown,
                        string | React.JSXElementConstructor<any>
                      >
                    | Iterable<React.ReactNode>
                    | React.ReactPortal
                    | Promise<
                        | string
                        | number
                        | bigint
                        | boolean
                        | React.ReactPortal
                        | React.ReactElement<
                            unknown,
                            string | React.JSXElementConstructor<any>
                          >
                        | Iterable<React.ReactNode>
                        | null
                        | undefined
                      >
                    | null
                    | undefined;
                },
                tabIndex: number,
              ) => {
                const globalIndex = pageIndex * PAGE_SIZE + tabIndex;
                return (
                  <TouchableOpacity
                    key={globalIndex}
                    style={styles.tabItem}
                    onPress={() => {
                      handleIndicatorPress(pageIndex);
                    }}
                  >
                    <View style={styles.iconContainer}>
                      <Image
                        source={{ uri: tab.icon.trim() }}
                        style={styles.icon}
                      />{' '}
                    </View>
                    <Text style={styles.label}>{tab.label}</Text>
                  </TouchableOpacity>
                );
              },
            )}
          </View>
        )}
        onMomentumScrollEnd={handleMomentumScrollEnd}
        scrollEventThrottle={16}
      />

      <View style={styles.indicatorContainer}>
        {pages.map((_, index) => (
          <TouchableOpacity
            key={index}
            style={styles.indicatorTouchable}
            onPress={() => handleIndicatorPress(index)}
          >
            <View
              style={[
                styles.indicatorLine,
                activeIndex === index ? styles.activeIndicatorLine : null,
              ]}
            />
          </TouchableOpacity>
        ))}
      </View>
    </View>
  );
};

export default SwiperNav;

const styles = StyleSheet.create({
  container: {
    width: '94%',
    alignSelf: 'center',
    borderRadius: 20,
    marginTop: 10,
    paddingVertical: 10,
    backgroundColor: '#ffffff',
    shadowColor: 'transparent',
  },
  page: {
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingHorizontal: 10,
  },
  tabItem: {
    alignItems: 'center',
    justifyContent: 'center',
    marginHorizontal: 5,
  },
  iconContainer: {
    width: 55,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  icon: {
    width: 35,
    height: 35,
    resizeMode: 'contain',
  },
  label: {
    marginTop: 5,
    fontSize: 12,
    color: '#333',
    textAlign: 'center',
  },
  indicatorContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 10,
  },
  indicatorTouchable: {
    paddingHorizontal: 4,
  },
  indicatorLine: {
    width: 10,
    height: 2,
    backgroundColor: '#ccc',
    borderRadius: 1,
  },
  activeIndicatorLine: {
    backgroundColor: '#fa2c19',
    width: 15,
  },
});
